import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:typed_data';
// hive save image

class Page6 extends StatefulWidget {
  @override
  _Page6State createState() => _Page6State();
}

class _Page6State extends State<Page6> {
  final Box imageBox = Hive.box('images');
  Uint8List? imageBytes;

  @override
  void initState() {
    super.initState();
    // 启动时从Hive加载图片
    imageBytes = imageBox.get('user_image');
  }

  Future<void> pickAndSaveImage() async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: ImageSource.gallery);
    if (pickedFile != null) {
      final bytes = await pickedFile.readAsBytes();
      await imageBox.put('user_image', bytes);
      setState(() {
        imageBytes = bytes;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('用户上传图片并用 Hive 保存')),
      body: Center(
        child: imageBytes != null ? Image.memory(imageBytes!) : Text('还没有选择图片'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: pickAndSaveImage,
        child: Icon(Icons.upload_file),
        tooltip: '上传图片',
      ),
    );
  }
}
